/*
 * Copyright (C) 2009 Rob Cash
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * MessageSourceValidationPanel.java
 */

package org.robcash.apps.messagepopup.view.wizard;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.robcash.apps.messagepopup.Main;
import org.robcash.apps.messagepopup.action.MessageSourceValidator;
import org.robcash.apps.messagepopup.view.components.MessageSourceValidatorStatusPanel;
import org.robcash.commons.swing.wizard.Wizard;
import org.robcash.commons.task.ThreadPoolExecutor;
import org.robcash.commons.swing.wizard.impl.BaseWizardPanel;
import org.robcash.commons.swing.wizard.model.WizardModel;

/**
 *
 * @author Rob
 */
public class MessageSourceValidationPanel
        extends BaseWizardPanel<MessageSourceValidatorStatusPanel>
        implements ChangeListener {

    private MessageSourceValidatorStatusPanel validationStatusDisplay;
    private Future<Boolean> task;

    public MessageSourceValidationPanel(String objectId) {
        super(objectId);
        validationStatusDisplay = new MessageSourceValidatorStatusPanel();
        validationStatusDisplay.addChangeListener(this);
        setComponent(validationStatusDisplay);
    }

    @Override
    public String getNextPanelId() {
        String nextPanelId = null;

        if ( task != null && task.isDone() ) {
            // Task exists and is done

            // Check on the outcome
            Boolean validationResult = Boolean.FALSE;
            try {
                validationResult = task.get(10, TimeUnit.MILLISECONDS);
            }
            catch(Exception e) {
                // Validation failed or we failed to get validation results.
                // No matter the reason, we don't want to return a next panel
            }
            if ( validationResult.booleanValue() ) {
                nextPanelId = WizardModel.NEXT;
            }
        }

        return nextPanelId;
    }

    /**
     * Indicates that the wizard panel is about to be displayed. This
     * implementation starts a message source validation task.
     * @param wizard Wizard that is about to display this panel
     */
    @Override
    public void aboutToDisplay(Wizard wizard) {
        super.aboutToDisplay(wizard);

        MessageSourceValidator validator = new MessageSourceValidator();
        SubscriptionModel model = (SubscriptionModel) wizard.getModel();
        validator.setMessageStore(model.getMessageStore());
        ThreadPoolExecutor executor = Main.getApplication().getExecutor();
        executor.addTaskListener(validationStatusDisplay);
        task = executor.submit(validator);
        validationStatusDisplay.setValidationTask(task);
    }

    /**
     * Indicates that the wizard panel is about to be displayed. This
     * implementation stops a message source validation task.
     * @param wizard Wizard that is about to hide this panel
     * @param saveWork Indicates whether or not work should be saved
     */
    @Override
    public void aboutToHide(Wizard wizard, boolean saveWork) {
        // If task is not done and not already cancelled, stop it
        if ( !task.isDone() && !task.isCancelled() ) {
            boolean cancelStatus = task.cancel(true);
            // TODO Change to commons logging
            System.out.println("Cancel of message source validation was " + (cancelStatus ? "" : "not ") + "successful");
        }
        ThreadPoolExecutor executor = Main.getApplication().getExecutor();
        if ( validationStatusDisplay != null ) {
            executor.removeTaskListener(validationStatusDisplay);
        }

        super.aboutToHide(wizard, saveWork);
    }

    /**
     * Receive notification that something has changed.
     * @param e Change event
     */
    public void stateChanged(ChangeEvent e) {
        if ( e.getSource().equals(validationStatusDisplay) ) {
            fireChangeListenerStateChanged(new ChangeEvent(this));
        }
    }

}
